package com.fixme4trade.security;

import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.fixme4trade.business.UserBC;
import br.gov.frameworkdemoiselle.security.Authenticator;
import br.gov.frameworkdemoiselle.security.User;

@Alternative
public class MyAuthenticator implements Authenticator{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private UserBC userBC;
	
	//@Inject
	//private HttpServletRequest request;
	
	@Inject
	HttpSession session;
	
	@Inject
	HttpServletRequest request;
	
	@Inject
	private Credentials credentials;
	
	public static String USER_SESSION_VARIABLE = "user";

	@Override
	public boolean authenticate() {		
		User user = null;
				
        if (session != null) {
        	session =  request.getSession(true);
        }
        user = (User) session.getAttribute(USER_SESSION_VARIABLE);
		                
        if (user == null) {
        	String username = credentials.getUsername();
        	String password = credentials.getPassword();        	        	
        	
        	if (username != null && password != null) {
        		boolean authOK = userBC.checkUsernamePassword(username,password); 
        		if(authOK) {        			
        			session.setAttribute(USER_SESSION_VARIABLE, userBC.getUserByUsername (username));
        		}
        		return authOK; 
        	} else return false;
        } else return false;
	}

	@Override
	public void unAuthenticate() {		
		if (session != null) {			
			session.invalidate();
		}		
	}

	@Override
	public User getUser() {		
		return (User) session.getAttribute(USER_SESSION_VARIABLE);
	}
}
